<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />

		<title>CSS居中示例</title>
		<style>
			/* 通用样式 */
			.container {
				margin: 20px;
				padding: 10px;
				border: 1px solid #ccc;
			}

			.title {
				color: #333;
				margin-bottom: 10px;
			}

			/* 示例1：文本水平居中 */
			.text-center {
				text-align: center;
				background: #f0f0f0;
				padding: 10px;
			}

			/* 示例2：块级元素水平居中 */
			.block-center {
				width: 500px;
				margin: 0 auto;
				background: #e0e0e0;
				padding: 10px;
			}

			/* 示例3：Flex布局居中 */
			.flex-center {
				display: flex;
				justify-content: center;/* 水平居中 */
				align-items: center; /* 垂直居中 */
				height: 200px;
				background: #f5f5f5;
			}

			.flex-item {
				padding: 20px;
				background: #d0d0d0;
			}

			/* 示例4：绝对定位居中 */
			.position-center {
				position: relative;
				height: 200px;
				background: #f5f5f5;
			}

			.position-item {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				background: #d0d0d0;
				padding: 20px;
			}

			/* 示例5：Grid布局居中 */
			.grid-center {
				display: grid;
				place-items: center;
				/* 简写方式实现水平垂直居中 */
				height: 200px;
				background: #f5f5f5;
			}

			.grid-item {
				background: #d0d0d0;
				padding: 20px;
			}

			/* 示例6：margin + position 居中 */
			.margin-position-center {
				position: relative;
				height: 200px;
				background: #f5f5f5;
			}

			.margin-position-item {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				margin: auto;
				width: 200px;
				height: 100px;
				background: #d0d0d0;
				text-align: center;
				line-height: 100px;
			}
		</style>
	</head>
	<body>
		<!-- 示例1：文本水平居中 -->
		<div class="container">
			<h3 class="title">1. 文本水平居中</h3>
			<div class="text-center">
				这是一段居中的文本
			</div>
		</div>

		<!-- 示例2：块级元素水平居中 -->
		<div class="container">
			<h3 class="title">2. 块级元素水平居中</h3>
			<div class="block-center">
				使用margin: 0 auto居中的块级元素
			</div>
		</div>

		<!-- 示例3：Flex布局居中 -->
		<div class="container">
			<h3 class="title">3. Flex布局居中</h3>
			<div class="flex-center">
				<div class="flex-item">Flex布局居中的元素</div>
			</div>
		</div>

		<!-- 示例4：绝对定位居中 -->
		<div class="container">
			<h3 class="title">4. 绝对定位居中</h3>
			<div class="position-center">
				<div class="position-item">绝对定位居中的元素</div>
			</div>
		</div>

		<!-- 示例5：Grid布局居中 -->
		<div class="container">
			<h3 class="title">5. Grid布局居中</h3>
			<div class="grid-center">
				<div class="grid-item">Grid布局居中的元素</div>
			</div>
		</div>

		<!-- 示例6：margin + position居中 -->
		<div class="container">
			<h3 class="title">6. margin + position居中</h3>
			<div class="margin-position-center">
				<div class="margin-position-item">
					margin + position居中
				</div>
			</div>
		</div>
	</body>
</html>